/****************************************************
 *
 * 项目名称：  com.heroh.db
 * All rights Reserved, Designed By 投资交易团队
 * @Copyright:2016-2021
 *
 ********************************************************/

package com.heroh.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 包名称： com.heroh.db
 * 类名称：ConnectionUtil
 * 类描述：TODO
 * 创建人：@author shengxiong.jian
 * 创建时间：2021/3/8/13:58
 */
public class ConnectionBean {

    /**
     * 数据库配置
     */
    private DbConfig dbConfig;

    /**
     * 数据库连接
     */
    private Connection conn = null;

    public ConnectionBean(DbConfig config) {
        this.dbConfig = config;
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public Connection getConnection() {
        try {
            Class.forName(dbConfig.getDriver());
            if (null == conn) {
                conn = DriverManager.getConnection(dbConfig.getUrl(), dbConfig.getUser(), dbConfig.getPassword());
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("get connection failure");
        }
        return conn;
    }

    /**
     * 关闭数据库连接
     */
    public void closeConnection() {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.err.println("close connection failure");
            }
        }
    }
}
